<?php

namespace App\Services;

use App\Exceptions\AppException;
use App\Models\Article;
use App\Models\Comment;

class CommentService
{

    public function getCount()
    {
        return Comment::count();
    }

    public function getCountAfterTime($time)
    {
        return Comment::where('created_at', '>', $time)->count();
    }

    public function getList(array $where = [], int $limit = 15)
    {
        $result = Comment::where($where)
            ->with(['article' => function ($query) {
                $query->select('id', 'title', 'status', 'published_at');
            }])
            ->orderBy('id', 'desc')
            ->paginate($limit);

        return [
            'items' => $result->items(),
            'total' => $result->total(),
            'limit' => $limit,
        ];
    }

    public function getNewList(int $limit)
    {
        return Comment::select('id', 'article_id', 'name')
            ->with(['article' => function ($query) {
                $query->select('id', 'title', 'status', 'published_at');
            }])
            ->orderBy('id', 'desc')
            ->limit($limit)
            ->get();
    }

    public function find(int $id)
    {
        return Comment::findOrFail($id);
    }

    public function reply(int $id, string $replyContent)
    {
        $comment = Comment::find($id);
        $comment->reply_content = $replyContent;
        $comment->save();
    }

    public function del(array $ids)
    {
        Comment::destroy($ids);
    }

    public function add(array $data)
    {
        $exists = Article::where('id', $data['article_id'])->where('status', 1)->exists();

        if (!$exists) {
            throw new AppException('文章ID无效');
        }

        Comment::create($data);
    }

}
